<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :width="1000"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #mapSlot="{}">
        <div id="search">
          <a-input
            v-model:value="searchValue"
            @keyup="seachAddress"
            @keydown="seachAddress"
            placeholder="请输入要搜索的位置"
            style="width: 91%; margin: 0px 2px 0 12px"
          />
          <a-button type="primary"
                    v-auth="SiteAuth.ADD"
                    @click="seachAddress">查询
          </a-button>
        </div>
        <div id="container">
        </div>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script setup lang="ts">
import {computed, ref, unref, nextTick, reactive} from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import {formSchema} from './site.data';
import {useMessage} from '@/hooks/web/useMessage';
import {getSiteApi, addSiteApi, editSiteApi, getSiteNoApi} from '@/api/core/site.api';
import {BasicModal, useModalInner} from '@/components/Modal';
import {BasicForm, useForm} from '@/components/Form';
import {listDeptApi} from '@/api/system/organize/dept.api';
import {SiteAuth} from "@/auth/core/site.auth";

/**
 * 地图js
 */
const searchValue = ref('')
const state = reactive({
  map: null,
  placeSearch: null,
  autoComplete: null,
  marker: null,
  form: {
    address: '',
    lng: '',
    lat: '',
  },
});
const emit = defineEmits(['success', 'register']);
const {createMessage} = useMessage();
const isUpdate = ref(true);
const [registerForm, {updateSchema, resetFields, setFieldsValue, validate}] = useForm({
  labelWidth: 80,
  schemas: formSchema,
  showActionButtonGroup: false,
});
const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
  resetFields();
  setModalProps({confirmLoading: false});
  isUpdate.value = !!data?.isUpdate;
  if (unref(isUpdate)) {
    const site = await getSiteApi(data.record.id);
    setFieldsValue({...site});
    searchValue.value = site.siteAddress;
    state.form.lng = site.longitude;
    state.form.lat = site.latitude;
  } else {
    const site = await getSiteNoApi();
    setFieldsValue({siteNo: site.siteNo});
    searchValue.value = '';
    state.form.lng = '';
    state.form.lat = '';
  }
  const treeData = await listDeptApi({
    id: unref(isUpdate) ? data.record.id : undefined,
    defaultNode: true,
    exNodes: unref(isUpdate),
  });
  updateSchema({field: 'areaId', componentProps: {treeData}});
  // let cpDataPage=await listCpApi() ;
  // let cpData=cpDataPage.items;
  // alert(JSON.stringify(cpData))
  // updateSchema({field: 'cpId', componentProps: {values:cpData}});

  AMapLoader.load({
    key: 'b9f21206c2955b9fc5490d7057d2fa78', // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [
      'AMap.ToolBar',
      'AMap.ControlBar',
      'AMap.AutoComplete',
      'AMap.PlaceSearch',
      'AMap.Geocoder',
      'AMap.Marker',
    ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  })
    .then((AMap) => {
      state.map = new AMap.Map('container', {
        // 设置地图容器id
        viewMode: "3D",  //  是否为3D地图模式
        zoom: 10, //  地图显示的缩放级别
        zooms: [2, 22], // 地图缩放范围
        resizeEnable: true  //  是否监控地图容器尺寸变化
        // jogEnable: false, //是否使用缓动效果，关闭平移惯性感觉舒服一些
      });

      let toolBar = new AMap.ToolBar({
        position: {
          top: '120px',
          right: '51px',
        },
      });
      state.geoCoder = new AMap.Geocoder({
        city: '全国', // 默认：“全国”
        radius: 1000, // 范围，默认：500
      });
      state.autoComplete = new AMap.AutoComplete({city: '全国'});
      state.placeSearch = new AMap.PlaceSearch({
        map: state.map
      })
      state.map.on('click', clickMap);
      state.map.addControl(toolBar); // 添加右上角的放大缩小
    })
    .catch((e) => {
      console.log(e);
    })
    .finally(() => {
      initCoord([state.form.lng, state.form.lat]);
    });

  // 坐标转换
  function initCoord(gps) {
    // 其他坐标转J02坐标
    AMap.convertFrom(gps, 'gps', function (status, result) {
      if (result.info === 'ok') {
        // state.form.lng = result.locations[0].lng;
        // state.form.lat = result.locations[0].lat;
        // nextTick(function () {
        //   removeMarker();
        //   setMapMarker();
        // });
        removeMarker();
        setMapMarker();
      }
    });
  }

  function clickMap(e) {
    // 点击地图事件
    if (!e && !e.lnglat) {
      return;
    }
    state.form.lng = e.lnglat.lng;
    state.form.lat = e.lnglat.lat;
    regeocoder();
    removeMarker(); // 先删除地图上标记点
    setMapMarker(); // 在添加新的标记点
  }

  // 设置标记


  // 设置标记
  function setMapMarker() {
    if (state.form.lng == '' && state.form.lat == '') {
      return;
    }
    state.map.setFitView();
    state.marker = new AMap.Marker({
      map: state.map,
      position: [state.form.lng, state.form.lat],
    });
    // toGetAddress()
    state.map.add(state.marker);
    state.map.setFitView();
  }

  // 清除标记
  function removeMarker() {
    if (state.marker) {
      state.map.remove(state.marker);
    }
  }

  // 坐标位置转换
  function regeocoder() {
    let lnglat = [state.form.lng, state.form.lat];
    state.geoCoder.getAddress(lnglat, (status, result) => {
      if (status === 'complete' && result.regeocode) {
        state.form.address = result.regeocode.formattedAddress; // 返回位置信息
        setFieldsValue({
          siteAddress: state.form.address,
        });
        setFieldsValue({
          longitude: state.form.lng,
        });
        setFieldsValue({
          latitude: state.form.lat,
        });
      }
    });
  }
});

// 关键字搜索
function seachAddress() {
  if (searchValue.value != '') {
    //清除地图上的覆盖物
    state.map.clearMap()
    state.map.plugin('AMap.PlaceSearch', () => {
      let placeSearch = new AMap.PlaceSearch({
        // city 指定搜索所在城市，支持传入格式有：城市名、citycode和adcode
        city: '010',
        map: state.map
      })
      let that = state.form
      placeSearch.search(searchValue.value, function (status, result) {
        if (status === 'error') {
          createMessage.error('已超过当日查询上限,请手动选择地址！');
        }
        // 查询成功时，result即对应匹配的POI信息
        var pois = result.poiList.pois
        for (var i = 0; i < pois.length; i++) {
          var poi = pois[i]
          var marker = []
          marker[i] = new AMap.Marker({
            position: poi.location, // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
            title: poi.name
          })
          // 将创建的点标记添加到已有的地图实例：
          state.map.add(marker[i])
        }
        state.map.setFitView()
        AMap.Event.addListener(placeSearch, 'markerClick', function (data) {
          let result = data
          //经纬度
          state.form.lng = result.event.lnglat.lng
          state.form.lat = result.event.lnglat.lat
          toGetAddress();
        })
      })
    })
  } else {
  }
}


function toGetAddress() {
  let lnglat = [state.form.lng, state.form.lat]
  state.geoCoder.getAddress(lnglat, (status, result) => {
    if (status === 'complete' && result.regeocode) {
      state.form.address = result.regeocode.formattedAddress; // 返回位置信息
      setFieldsValue({
        siteAddress: state.form.address,
      });
      setFieldsValue({
        longitude: state.form.lng,
      });
      setFieldsValue({
        latitude: state.form.lat,
      });
    }
  })
}


/** 标题初始化 */
const getTitle = computed(() => (!unref(isUpdate) ? '新增网点' : '编辑网点'));

/** 提交按钮 */
async function handleSubmit() {
  try {
    const values = await validate();
    setModalProps({confirmLoading: true});
    unref(isUpdate)
      ? await editSiteApi(values).then(() => {
        closeModal();
        createMessage.success('编辑网点成功！');
      })
      : await addSiteApi(values).then(() => {
        closeModal();
        createMessage.success('新增网点成功！');
      });
    emit('success');
  } finally {
    setModalProps({confirmLoading: false});
    map?.destroy();
  }
}
</script>
<style scoped>
#container {
  width: 99%;
  height: 200px;
  margin-left: 10px;
}
</style>
